package com.lucenex.bean;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

import lombok.Getter;
import lombok.Setter;

public class Dic {

	@Getter
	@Setter
	private String extDictPath;
	@Getter
	@Setter
	private String extStopwordPath;
	@Getter
	@Setter
	private Map<String, Set<String>> thesaurus;
	
	private Logger log = Logger.getLogger(Dic.class);


	/**
	 * 初始化 词库 (自动执行 无需手动)
	 */
	public void init() {
		if(this.thesaurus == null) {
			log.info("加载字典");
			Map<String, Set<String>> thesaurus = new HashMap<String, Set<String>>();
			//启用词
			if(this.extDictPath != null) {
				thesaurus.put("ext_dict", exe(this.extDictPath));
			}
			//停用词
			if(this.extStopwordPath != null) {
				thesaurus.put("ext_stopwords", exe(this.extStopwordPath));
			}
			setThesaurus(thesaurus);
		}
	}

	private Set<String> exe(String path){
		Set<String> set = new HashSet<>();
		List<InputStream> list = new ArrayList<>();
		getExtend(list, path);
		for (InputStream in : list) {
			BufferedReader br = null;
			InputStreamReader inr = null;
			try {
				inr = new InputStreamReader(in, "UTF-8");
				br = new BufferedReader(inr);
				do {
					set.add(br.readLine());
				} while (br.readLine() != null);
			} catch (Exception e) {
				log.error("加载文件流 ERROR", e);
			}finally {
				try {
					if(br != null) {
						br.close();
					}
					if(inr != null) {
						inr.close();
					}
					if(in != null) {
						in.close();
					}
				} catch (Exception e2) {
					log.error("关闭文件流 ERROR", e2);
				}
			}
		}
		return set;
	}

	private void getExtend(List<InputStream> list, String path){
		File f = new File(path);
		//列出所有文件 及目录
		if(f.exists()) {
			File[] files = f.listFiles();
			for (int i = 0; i < files.length; i++) {
				File file = files[i];
				if(file.isDirectory()) {
					//目录
					getExtend(list,file.getAbsolutePath());
				}else {
					try {
						//文件不等于空  并且 是 .dic 结尾 文件
						if(file.exists() && file.getName().endsWith(".dic")) {
							list.add(new FileInputStream(file));
						}
					} catch (FileNotFoundException e) {
						log.error("词典文件流 ERROR", e);
					}
				}
			}
		}
	}

}
